import React, {
  FC,
  ReactElement,
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
} from 'react'
import { Row, Col, Form, Input, DatePicker, Button, InputNumber } from 'antd'
import style from '../index.less'
import commonStyle from '@/pages/publicStyle'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import moment from 'moment'
import { ActivityList, SubmitForm } from '../../index.d'
import { dataFormat2 } from '@/untils/dictionaries'

const RangePicker: any = DatePicker.RangePicker
const layout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 14 },
}

const tailLayout = {
  wrapperCol: { offset: 0, span: 22 },
}
interface IProps {
  SignUpData: any
  saveFormData: () => void
  isDrop: boolean
  typeId: string
}
const initStyle = {
  checkedType: {
    background: '#1890ff',
    color: '#fff',
  },
}

const SignUp = forwardRef((props: IProps, ref: any): ReactElement => {
  const [form] = Form.useForm()
  const [activityList, setActivityList] =
    useState<ActivityList[]>(initActivityList)
  const [customField, setCustomField] = useState([
    {
      key: '',
      value: '',
    },
  ])
  const [submitForm, setSubmitForm] = useState<SubmitForm>({
    startDate: '',
    endDate: '',
    numberLimit: 1,
  })
  // 返回完成校验数据
  const getOverFormData = () => {
    let requiredEntryForms: any = activityList.filter(item => item.checked)
    let optionalEntryForms: any = []
    customField.forEach((item, index) => {
      if (item.key) {
        let length = Math.floor(Math.random() * 100) + 1
        optionalEntryForms.push({
          key: item.key,
          value: item.value,
          inputType: index,
          length,
          inputVerifyType: item.value,
        })
      }
    })
    return {
      activityType: props.typeId === 'SignUp' ? '1' : '3',
      ...submitForm,
      requiredEntryForms: requiredEntryForms.map((item: any, index: number) => {
        delete requiredEntryForms[index].checked
        return requiredEntryForms[index]
      }),
      optionalEntryForms,
    }
  }
  useImperativeHandle(ref, () => {
    return {
      form: form,
      getOverFormData: getOverFormData,
    }
  })
  const customFieldChange = (value: string, index: number) => {
    setCustomField(
      customField.map((citem, cindex) => {
        if (index === cindex) {
          citem.key = value
          citem.value = value + cindex
        }
        return citem
      }),
    )
  }
  const addCustomField = () => {
    setCustomField([...customField, { key: '', value: '' }])
  }
  // 修改活动日期
  const activityTimeChange = (dataString: string[]) => {
    let oldFormData = JSON.parse(JSON.stringify(submitForm))
    oldFormData.startDate = dataString[0]
    oldFormData.endDate = dataString[1]
    setSubmitForm(oldFormData)
  }
  // 初始化数据
  useEffect(() => {
    if (props.SignUpData) {
      let oldFormData = JSON.parse(JSON.stringify(props.SignUpData))
      form.setFieldsValue({
        activityTime: [
          oldFormData.startDate
            ? moment(oldFormData.startDate, dataFormat2)
            : undefined,
          oldFormData.endDate
            ? moment(oldFormData.endDate, dataFormat2)
            : undefined,
        ],
        numberLimit: oldFormData.numberLimit,
      })
      setSubmitForm({
        startDate: oldFormData.startDate,
        endDate: oldFormData.endDate,
        numberLimit: oldFormData.numberLimit,
      })
      if (
        props.SignUpData.optionalEntryForms &&
        props.SignUpData.optionalEntryForms.length !== 0
      ) {
        setCustomField(
          props.SignUpData.optionalEntryForms.map((item: any) => ({
            key: item.key,
            value: item.value,
          })),
        )
      }
      setActivityList(
        activityList.map(item => {
          let sameIndex = props.SignUpData?.requiredEntryForms?.find(
            (rItem: any) => rItem.key === item.key,
          )
          if (sameIndex) {
            item.checked = true
          }
          return item
        }),
      )
    }
  }, [])
  // 折叠时暂存数据
  useEffect(() => {
    return () => {
      if (!props.isDrop) {
        props.saveFormData(getOverFormData(), `${props.typeId}Data`)
      }
    }
  }, [props.isDrop])
  const activityCheck = (rules: any, value: any, callback: any) => {
    try {
      if (submitForm.startDate && submitForm.endDate) {
        return Promise.resolve()
      } else {
        return Promise.reject('请选择活动日期')
      }
    } catch (error) {
      callback(error)
    }
  }
  const projectNameCheck = (index: number) => {
    return customField[index].key === ''
  }
  const { detailFormTitle, formBorderBox, activityTypeItem, activityTypeBox } =
    style
  const { checkedType } = initStyle
  const { mt20, mr10, completeW } = commonStyle
  return (
    <div>
      <Form {...layout} form={form}>
        <div className={detailFormTitle}>基本信息</div>
        <div className={formBorderBox}>
          <Row>
            <Col span={12}>
              <Form.Item
                name="activityTime"
                label="活动时间"
                rules={[{ required: true, validator: activityCheck }]}
              >
                <RangePicker
                  format={dataFormat2}
                  onChange={(dates: moment.Moment[], datestrings: string[]) => {
                    activityTimeChange(datestrings)
                  }}
                  showTime
                  style={completeW}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="numberLimit"
                label={props.typeId === 'SignUp' ? '报名人数' : '门票数量'}
              >
                <InputNumber
                  style={completeW}
                  min={1}
                  max={9999999}
                  formatter={value => `${Math.floor(value || 1)}`}
                  onChange={value => {
                    setSubmitForm({
                      ...submitForm,
                      numberLimit: Number(value),
                    })
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
        </div>
        <div className={detailFormTitle} style={mt20}>
          选择您希望活动参加者填写的信息
        </div>
        <div className={`${formBorderBox} ${activityTypeBox}`}>
          {activityList.map((item, index) => (
            <div
              key={index}
              className={activityTypeItem}
              onClick={() => {
                setActivityList(
                  activityList.map(items => {
                    if (items.value === item.value)
                      items.checked = !items.checked
                    return items
                  }),
                )
              }}
              style={{ ...(item.checked ? checkedType : '') }}
            >
              {item.key}
            </div>
          ))}
        </div>
        <div className={detailFormTitle} style={mt20}>
          可添加补充项目
        </div>
        <div className={formBorderBox}>
          {customField.map((item, index) => (
            <Row key={index}>
              <Col span={8}>
                <Form.Item
                  name={['project' + index]}
                  label="项目名称"
                  rules={[
                    {
                      required: true,
                      validator: (rules: any, value: any, callback: any) => {
                        if (projectNameCheck(index)) {
                          return Promise.reject('请填写项目名称')
                        } else {
                          return Promise.resolve()
                        }
                      },
                    },
                  ]}
                  {...tailLayout}
                >
                  <Input
                    value={item.key}
                    onChange={e => {
                      customFieldChange(e.target.value, index)
                    }}
                    placeholder="请输入项目名称，如爱好"
                    style={{ width: '95%' }}
                  />
                  <DeleteOutlined
                    style={{
                      cursor: 'pointer',
                      color: '#eb2f96',
                      marginLeft: '5px',
                    }}
                    onClick={() => {
                      setCustomField(
                        customField.filter((citem, cindex) => index !== cindex),
                      )
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
          ))}
          <Row style={mt20}>
            <Col span={7}>
              <Button
                style={completeW}
                type="dashed"
                icon={<PlusOutlined />}
                onClick={() => {
                  addCustomField()
                }}
              >
                添加
              </Button>
            </Col>
          </Row>
        </div>
      </Form>
    </div>
  )
})
export default SignUp
const initActivityList = [
  {
    key: '姓名',
    value: 'name',
    checked: false,
    inputType: 0,
    length: 10,
    inputVerifyType: 'name',
  },
  {
    key: '性别',
    value: 'sex',
    checked: false,
    inputType: 1,
    length: 10,
    inputVerifyType: 'sex',
  },
  {
    key: '图片',
    value: 'photo',
    checked: false,
    inputType: 2,
    length: 10,
    inputVerifyType: 'photo',
  },
  {
    key: '手机号',
    value: 'phone',
    checked: false,
    inputType: 3,
    length: 10,
    inputVerifyType: 'phone',
  },
  {
    key: '生日',
    value: 'birthday',
    checked: false,
    inputType: 4,
    length: 10,
    inputVerifyType: 'birthday',
  },
  {
    key: 'QQ号',
    value: 'QQ',
    checked: false,
    inputType: 5,
    length: 10,
    inputVerifyType: 'QQ',
  },
  {
    key: '邮箱',
    value: 'email',
    checked: false,
    inputType: 6,
    length: 10,
    inputVerifyType: 'email',
  },
  {
    key: '学院',
    value: 'school',
    checked: false,
    inputType: 7,
    length: 10,
    inputVerifyType: 'school',
  },
  {
    key: '年级',
    value: 'lev',
    checked: false,
    inputType: 8,
    length: 10,
    inputVerifyType: 'lev',
  },
  {
    key: '班级',
    value: 'class',
    checked: false,
    inputType: 9,
    length: 10,
    inputVerifyType: 'class',
  },
  {
    key: '学号',
    value: 'No',
    checked: false,
    inputType: 10,
    length: 10,
    inputVerifyType: 'No',
  },
  {
    key: '特长',
    value: 'hopy',
    checked: false,
    inputType: 11,
    length: 10,
    inputVerifyType: 'hopy',
  },
  {
    key: '备注',
    value: 'remark',
    checked: false,
    inputType: 12,
    length: 10,
    inputVerifyType: 'remark',
  },
]
//
